<?php
namespace App\Repositories;

use App\Models\ChinaArea;
use App\Models\Tag;
use App\Models\Topic;
use App\Models\Comment;
use App\Models\CommentDetail;
use App\Models\User;
use App\Models\Forum;
use App\Models\AttachmentRelationship;
use App\Repositories\AttachmentRepository;
use Illuminate\Http\Request;
use App\Traits\ContentJson;
use App\Events\TopicCreated;
use Illuminate\Support\Facades\DB;

class TopicRepository
{
    use ContentJson;


    /**
     * 创建帖子
     * @param Request $request
     * @param User $user
     * @return number[]|string[]|array[]
     */
    public function create(Request $request, User $user)
    {
        $result = DB::transaction(function () use ($request, $user) {
            $forum = Forum::query()->findOrFail($request->fid);
            //创建话题
            $topicType = $request->get('type', Topic::TYPE_GENERAL);
            $topicData = $request->only(['title', 'action_time', 'action_location', 'longitude', 'latitude', 'action_province', 'action_city', 'action_district']);
            if ($topicType == Topic::TYPE_REPORT && $request->routeIs('api.*')) {
                $topicData['action_time'] = sprintf('%s %s', $request->action_date, $request->action_time);
            }

            $uid = $user->id;
            $topicData['type'] = $topicType;
            $topicData['fid'] = $forum->id;
            $topicData['uid'] = $uid;
            $topicData['last_comment_time'] = time();
            $topic = Topic::create($topicData);
            $contentArr = CommentRepository::getContents($request->get('content_detail'));
            //创建主楼
            $comment = $topic->mainFloor()->create([
                'uid' => $topic->uid,
                'floor_num' => 1,//创建帖子时候创建的评论，肯定是1楼
                'is_main_floor' => 1,
                'detail_excerpt' => CommentRepository::getDetailExcerpt($contentArr['contents']),
            ]);
            //创建主楼详情
            $commentDetail = $comment->detail()->create([
                'content' => $contentArr['contents'],
            ]);
            CommentRepository::saveDetailImages($comment, $commentDetail, $contentArr['images']);

            //保存隐藏部分
            if ($request->get('has_hide')) {
                $contentArr = CommentRepository::getContents($request->get('content_hide'));
                $commentHide = $comment->hide()->create([
                    'content' => $contentArr['contents'],
                    'require_reply' => intval($request->require_reply),
                    'require_score' => intval($request->require_score),
                ]);
                CommentRepository::saveDetailImages($comment, $commentHide, $contentArr['images']);
            }
            //标签部分
            $tagIdArr = $request->get('tags');
            if (!empty($tagIdArr)) {
                $tags = Tag::query()->findMany($tagIdArr);
                $topic->tags()->saveMany($tags);
            }

            event(new TopicCreated($topic));

            return normalize(RET_OK, MSG_OK, [
                'topic' => $topic,
                'forum' => $forum,
            ]);
        });

        return $result;

    }

    /**
     * 更新帖子。有标题、详情及其他可以更新。所属版块不可以，是单独的操作
     *
     * @param Request $request
     * @param $id
     * @return array
     */
    public function update(Request $request, $id)
    {

        $result = DB::transaction(function () use ($request, $id) {
            if (is_numeric($id)) {
                $topic = Topic::with('mainFloor')->withTrashed()->findOrFail($id);
            } else {
                $topic = Topic::with('mainFloor')->withTrashed()->where('key', $id)->firstOrFail();
            }
            //更新话题
            $topicData = $request->only(['title', 'action_time', 'action_location', 'longitude', 'latitude', 'action_province', 'action_city', 'action_district']);
            $topicType = $request->get('type', Topic::TYPE_GENERAL);
            if ($topicType == Topic::TYPE_REPORT && $request->routeIs('api.*')) {
                $topicData['action_time'] = sprintf('%s %s', $request->action_date, $request->action_time);
            }
            $topic->update($topicData);
            //更新主楼
            (new CommentRepository())->update($request, $topic->mainFloor->id);

            //更新标签
            $tagIdArr = $request->get('tags');
            if (!empty($tagIdArr)) {
                $tags = Tag::query()->findMany($tagIdArr);
                $topic->tags()->sync($tags);
            }

            return normalize(RET_OK, MSG_OK, $topic);
        });

        return $result;

    }

    /**
     * 更改敏感度
     *
     * @param $tid
     * @param $sensitivity
     * @return bool
     */
    public function changeSensitivity($tid, $sensitivity)
    {
        $result = DB::transaction(function () use ($tid, $sensitivity) {
            $topic = Topic::query()->findOrFail($tid);
            $topic->sensitivity = $sensitivity;
            return $topic->save();
        });
        return $result;
    }

    public function provinceCityDistrict(Request $request)
    {
        $fields = ['id', 'parent_id', 'code', 'name'];
        $provinceList = ChinaArea::query()->where('parent_id', 1)->get($fields);
        $provinceId = $request->get('province_id', $provinceList->first()->id);
        $cityList = ChinaArea::query()->where('parent_id', $provinceId)->get($fields);
        $cityId = $request->get('city_id', $cityList->first()->id);
        $districtList = ChinaArea::query()->where('parent_id', $cityId)->get($fields);
        $result = [
            $provinceList->toArray(),
            $cityList->toArray(),
            $districtList->toArray()
        ];
        return $result;
    }

    /**
     * 返回帖子详情数据
     *
     * @param int $tid
     * @param int $page
     * @param int $cid
     * @return array
     */
    public function topicDetailData($tid, $page, $cid = 0)
    {
        /** @var \App\Models\User $user */
        $user = auth_user();
        //帖子一取回，前端帖子列表模板共用一套，需要帖子数据
        $topic = null;
        $canSeeTopicHide = 0;
        $with = [
            'topic', 'user', 'detail', 'hide',
            'firstComments', 'firstComments.user', 'firstComments.detail',
            'firstComments.parentComment', 'firstComments.parentComment.user',
        ];
        if ($page <= 1 && !$cid) {
            //页码不大于1，且没提供 cid，才是详情首页，需要返回帖子及隐藏部分
            $topic = Topic::query()->findOrFail($tid);
            $canSeeTopicHideResult = $user->canSeeTopicHide($topic);
            $canSeeTopicHide = $canSeeTopicHideResult['result'];
            if ($canSeeTopicHide) {
                $topic->load('tags');
            }
        }

        $options = [
            'with' => $with,
            'tid' => $tid,
            'pid' => 0,
            'id' => $cid,
            'include_is_liked' => 1,
            'page' => $page,
            'per_page' => Topic::DETAIL_COMMENT_PAGE_SIZE
        ];
        $comments = (new CommentRepository())->getList($options);

        $result = [
            'comments' => $comments,
            'topic' => $topic,
            'can_see_topic_hide' => $canSeeTopicHide
        ];

        return $result;
    }

    /**
     * 评论详情数据
     *
     * @param $rootId
     * @param $page
     * @param int $cid
     * @return array
     */
    public function commentDetailData($rootId, $page, $cid = 0)
    {
        $with =  ['user', 'detail', 'parentComment', 'parentComment.user'];
        $options = [
            'with' => $with,
            'root_id' => $rootId,
            'id' => $cid,
            'include_is_liked' => 1,
            'page' => $page,
            'per_page' => Topic::DETAIL_COMMENT_PAGE_SIZE
        ];
        $comments = (new CommentRepository())->getList($options);
        $result = [
            'comments' => $comments,
        ];

        return $result;
    }


}